<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>作业-头像上传</title>
  <link rel="stylesheet" href="./css/bootstrap.min.css">
  <style>
    .thumb-box {
      text-align: center;
      margin-top: 50px;
    }

    .thumb {
      width: 250px;
      height: 250px;
      object-fit: cover;
      border-radius: 50%;
    }
  </style>
</head>

<body>
  <div class="thumb-box">
    <!-- 头像 -->
    <img src="./images/cover.jpg" class="img-thumbnail thumb" alt="">
    <div class="mt-2">
      <!-- 文件选择框 -->
      <!-- accept 属性表示可选择的文件类型 -->
      <!-- image/* 表示只允许选择图片类型的文件 -->
      <input type="file" id="iptFile" accept="image/*" style="display: none;">
      <!-- 选择头像图片的按钮 -->
      <button class="btn btn-primary" id="btnChoose">选择 & 上传图片</button>
    </div>
  </div>

  <script src="./lib/axios.js"></script>
  <script>

    axios.defaults.baseURL = 'http://www.itcbc.com:3006'

    // ～～按钮触发单击事件
    document.querySelector('#btnChoose').addEventListener('click', () => {
      document.querySelector('#iptFile').click()
    })

    // ～～文件内容上传
    document.querySelector('#iptFile').addEventListener('change', function () {
      // ～～判断
      if (this.files.length > 0) {
        let fileObj = this.files[0]
        if (fileObj.size > 500 * 1024) {
          return alert('图片大小不能超过500kb~')
        }
        let picType = ['image/png', 'image/jpeg']
        if (!picType.includes(fileObj.type)) {
          return alert('图片类型只能上传jpeg、png格式~')
        }

        // FormData
        let ho = new FormData()
        ho.append('avatar', fileObj)
        axios.post('/api/formdata', ho).then(({ data: res }) => {
          document.querySelector('img').src = res.data.filename
        })
      }
    })
  </script>

</body>

</html>